package com.sdtele.tta.operation;

import java.io.File;
import java.util.List;
import com.sdtele.tta.dac.Dac;
import com.sdtele.tta.models.Doc;
import com.sdtele.tta.models.JsonRequest;
import com.sdtele.tta.models.JsonResponse;
import com.sdtele.tta.models.Task;
import com.sdtele.tta.models.User;

/**
 * 操作类实现：GetUser(json.operation=getUser)
 * 
 * @author XCream
 */
public class OperationDelTask extends Operation {

	@Override
	public JsonResponse handle(JsonRequest jsonRequest) {
		JsonResponse jres = new JsonResponse();
		User curUser = (User) request.getSession().getAttribute("user");

		if (curUser != null) {
			long taskId = jsonRequest.getJsonObject().get("taskId").getAsLong();
			Task task = Dac.getInstance().getTaskbyTaskid(taskId);
			if (task != null) {
				if (curUser.getId() == task.getOwnerId()) {
					List<Task> subTaskList = Dac.getInstance().getSubTask(taskId);
					if (subTaskList != null) {
						for (Task subTask : subTaskList) {
							subTask.setFatherTaskId(0);
							Dac.getInstance().chgTask(subTask);
						}
					}

					List<Doc> docList = Dac.getInstance().getDocsOfTask(taskId);
					if (docList != null) {
						if (Dac.getInstance().delDocbyTaskid(taskId)) {
							for (Doc doc : docList) {
								String realPath = doc.getRealPath();
								File docFile = new File(realPath);
								if (docFile.exists())
									docFile.delete();
							}
						} else {
							jres.setStatus(1);
							jres.setMessage("未知错误，删除附件失败");
							return jres;
						}
					}
					if (Dac.getInstance().getResponse(taskId) != null)
						Dac.getInstance().delTaskResponse(taskId);

					if (!Dac.getInstance().delTaskoperation(taskId)) {
						jres.setStatus(1);
						jres.setMessage("未知错误，删除实施人、分阅人失败");
						return jres;
					}
					if (!Dac.getInstance().delTask(taskId)) {
						jres.setStatus(1);
						jres.setMessage("未知错误，删除主任务失败");
						return jres;
					}
					jres.setStatus(0);
					jres.setMessage("删除任务成功");
				} else {
					jres.setStatus(1);
					jres.setMessage("您没有权限删除此任务");
				}

			}

		} else {
			jres.setStatus(1);
			jres.setMessage("用户未登录");
		}
		return jres;
	}
}
